package com.dycong.common.IO.netty.frame_coder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.logging.Logger;

/**
 * Created by dycong on 2017/3/13.
 */
public class EchoServer {

    Logger logger = Logger.getLogger(EchoServer.class.getName());
    private   int PORT;
    private static final int MAX_FRAME_LENGTH = 1024 * 1024;
    private static final int LENGTH_FIELD_LENGTH = 4;
    private static final int LENGTH_FIELD_OFFSET = 2;

    public EchoServer(int port) {
        this.PORT = port;
    }

    public static void main(String[] args) {
        if (args.length != 0)
            new EchoServer(Integer.valueOf(args[0])).start();
        else
            new EchoServer(9090).start();
    }

    private void start() {
        NioEventLoopGroup group1 = new NioEventLoopGroup();
        NioEventLoopGroup group2 = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(group1,group2)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(PORT))
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializerServer());

            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            System.out.println(Thread.currentThread().getName());

            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {

        } finally {
            try {
                group1.shutdownGracefully().sync();
                group2.shutdownGracefully().sync();
            } catch (InterruptedException e) {

            }
        }
    }

}
